package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.nativestick.StickyGridHeadersSimpleAdapter;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/7.
 */

public class LocalManageDayAdapter extends BaseAdapter implements
        StickyGridHeadersSimpleAdapter {

    private Resources mResource;
    private LayoutInflater mInflater;
    private Context mContext;
    private List<YNNativeImage> hasHeaderIdList;
    private boolean isSelectStatus;     // 是否在选择状态
    private ImageLoader imageLoader;
    private Map<String, Boolean> click = new HashMap<>();
    private Map<String, ImageView> headView = new HashMap<>();
    private List<String> localUrl = new ArrayList<>();
    private List<String> list = new ArrayList<>();
    private boolean dayTime;
    private Map<String, List<String>> dateUrl = new HashMap<>();
    private Map<String, List<YNNativeImage>> dayMap = new HashMap<>();
    private Map<String, List<YNNativeImage>> monMap = new HashMap<>();

    public void setResource(Resources mResource) {
        this.mResource = mResource;
    }

    public LocalManageDayAdapter(Context mContext, List<YNNativeImage> hasHeaderIdList, boolean isSelectStatus, boolean dayTime, Map<String, List<YNNativeImage>> dayMap, Map<String, List<YNNativeImage>> monMap) {
        mInflater = LayoutInflater.from(mContext);
        this.mContext = mContext;
        this.hasHeaderIdList = hasHeaderIdList;
        this.isSelectStatus = isSelectStatus;
        this.dayTime = dayTime;
        this.dayMap = dayMap;
        this.monMap = monMap;
        imageLoader = ImageLoader.getInstance();
        if (YNSingleton.getInstance().getNativePhoto().size() == 0 || YNSingleton.getInstance().getNativePhoto() != hasHeaderIdList) {
            YNSingleton.getInstance().setNativePhoto(hasHeaderIdList);
        }
        initData();
    }

    private void initData() {
        if (SelectedImg.mSelectedImage.size() != 0) {
            dateUrl.clear();
            for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                String path = SelectedImg.mSelectedImage.get(i);
                if (dateUrl.containsKey(getTime(path, dayTime))) {
                    List<String> strings = dateUrl.get(getTime(path, dayTime));
                    strings.add(path);
                    dateUrl.put(getTime(path, dayTime), strings);
                } else {
                    List<String> localUrl = new ArrayList<>();
                    localUrl.add(path);
                    dateUrl.put(getTime(path, dayTime), localUrl);
                }
            }
        }
    }


    public void setSelectStatus(boolean isSelectStatus) {
        this.isSelectStatus = isSelectStatus;
    }

    @Override
    public long getHeaderId(int position) {
        return hasHeaderIdList.get(position).getSection();
    }

    @Override
    public int getCount() {
        return hasHeaderIdList.size();
    }

    @Override
    public Object getItem(int position) {
        return hasHeaderIdList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder mViewHolder;
        if (convertView == null) {
            mViewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.yn_import_pic, parent, false);
            mViewHolder.mImageView = (SimpleDraweeView) convertView.findViewById(R.id.native_item_image);
            mViewHolder.mNative_item_select = (ImageView) convertView.findViewById(R.id.native_item_select);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        final String path = hasHeaderIdList.get(position).getPath();
        mViewHolder.mImageView.setTag(path);

        mViewHolder.mImageView.setImageResource(R.drawable.pic_null);

        if (mResource != null) {
            mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("picture_unselected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
        } else {
            mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_no_select_import);
        }

        Uri uri = Uri.parse("file://" + path);
        ImageOptHelper.showFrescoNative(uri, mViewHolder.mImageView, mContext);

        final int screenWidth = DisplayUtils.getScreenWidthPixels((Activity) mContext);
        int horizontalSpacing = DisplayUtils.dp2px(mContext, 2);
        // 设置图片宽高
        if (dayTime) {
            int itemWidth = (screenWidth - 2 * horizontalSpacing) / 3;
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(itemWidth, itemWidth);
            mViewHolder.mImageView.setLayoutParams(params);
        } else {
            int itemWidth = (screenWidth - 3 * horizontalSpacing) / 4;
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(itemWidth, itemWidth);
            mViewHolder.mImageView.setLayoutParams(params);
        }
//        Log.d("yuhao", "itemWidth");
        mViewHolder.mNative_item_select.setVisibility(View.VISIBLE);
        mViewHolder.mImageView.setColorFilter(null);
        // 图片选择事件
        mViewHolder.mImageView.setOnClickListener(new View.OnClickListener() {
            //选择，则将图片变暗，反之则反之
            @Override
            public void onClick(View v) {
                // 已经选择过该图片
                if (SelectedImg.mSelectedImage.contains(path)) {
                    SelectedImg.mSelectedImage.remove(path);
                    List<String> strings = dateUrl.get(getTime(path, dayTime));
                    strings.remove(path);
                    dateUrl.put(getTime(path, dayTime), strings);
                    if (mResource != null) {
                        mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("picture_unselected", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                    } else {
                        mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_no_select_import);
                    }
                    mViewHolder.mImageView.setColorFilter(null);
//                    ScaleAnimation scaleAnimation = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//                    scaleAnimation.setFillAfter(true);
//                    mViewHolder.mImageView.setAnimation(scaleAnimation);
//                    scaleAnimation.startNow();

                    //取消全选
                    click.put(getTime(path, dayTime), false);
                    if (headView.get(getTime(path, dayTime)) != null) {
                        headView.get(getTime(path, dayTime)).setImageResource(R.drawable.pic_no_select_import);
                    }
                    headView.put(getTime(path, dayTime), null);
                } else
                // 未选择该图片
                {
                    SelectedImg.mSelectedImage.add(path);
                    if (dateUrl.containsKey(getTime(path, dayTime))) {
                        List<String> strings = dateUrl.get(getTime(path, dayTime));
                        strings.add(path);
                        dateUrl.put(getTime(path, dayTime), strings);
                    } else {
                        List<String> localUrl = new ArrayList<>();
                        localUrl.add(path);
                        dateUrl.put(getTime(path, dayTime), localUrl);
                    }
//                    Log.d("yuhao", "size="+dayMap.get(getTime(path,dayTime)).size());
                    if (dayTime == true && dayMap.get(getTime(path, dayTime)).size() == dateUrl.get(getTime(path, dayTime)).size()) {
                        click.put(getTime(path, dayTime), true);
                        notifyDataSetChanged();
                        Log.d("yuhao", "time=" + getTime(path, dayTime));
                    } else if (dayTime == false && monMap.get(getTime(path, dayTime)).size() == dateUrl.get(getTime(path, dayTime)).size()) {
                        click.put(getTime(path, dayTime), true);
                        notifyDataSetChanged();
                    }
                    if (mResource != null) {
                        mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                    } else {
                        mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_select_import);
                    }
                    mViewHolder.mImageView.setColorFilter(Color.parseColor("#33000000"));
//                    ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//                    scaleAnimation.setFillAfter(true);
//                    mViewHolder.mImageView.setAnimation(scaleAnimation);
//                    scaleAnimation.startNow();
                }
            }
        });
        // 响应选择效果
        if (SelectedImg.mSelectedImage.contains(path)) {
            if (mResource != null) {
                mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            } else {
                mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_select_import);
            }
            mViewHolder.mImageView.setColorFilter(Color.parseColor("#33000000"));
//            ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//            scaleAnimation.setFillAfter(true);
//            mViewHolder.mImageView.setAnimation(scaleAnimation);
//            scaleAnimation.startNow();
        } else {
            if (mResource != null) {
                mViewHolder.mNative_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            } else {
                mViewHolder.mNative_item_select.setImageResource(R.drawable.pic_no_select_import);
            }
            mViewHolder.mImageView.setColorFilter(null);
//            ScaleAnimation scaleAnimation = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//            scaleAnimation.setFillAfter(true);
//            mViewHolder.mImageView.setAnimation(scaleAnimation);
//            scaleAnimation.startNow();
        }

//        // 点击图片大图查看
//        mViewHolder.mImageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(mContext, NativePreviewActivity.class);
//                intent.putExtra(CommonConstants.YNDATAS, position);
//                mContext.startActivity(intent);
//            }
//        });
        return convertView;
    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        final HeaderViewHolder mHeaderHolder;
        if (convertView == null) {
            mHeaderHolder = new HeaderViewHolder();
            convertView = mInflater.inflate(R.layout.yn_import_pic_header, parent, false);
            mHeaderHolder.mTextView = (TextView) convertView.findViewById(R.id.native_header_time);
            mHeaderHolder.mimageButton = ((ImageView) convertView.findViewById(R.id.all_pic_select));
            convertView.setTag(mHeaderHolder);
        } else {
            mHeaderHolder = (HeaderViewHolder) convertView.getTag();
        }
        mHeaderHolder.mTextView.setText(hasHeaderIdList.get(position).getTime());
        //该位置是被点击全选还是取消全选还是没有被点击过
        if (!click.containsKey(mHeaderHolder.mTextView.getText().toString().trim()) || !click.get(mHeaderHolder.mTextView.getText().toString().trim())) {
            mHeaderHolder.mimageButton.setImageResource(R.drawable.pic_no_selece_all_import);
        } else {
            mHeaderHolder.mimageButton.setImageResource(R.drawable.pic_select_import);
            headView.put(mHeaderHolder.mTextView.getText().toString().trim(), mHeaderHolder.mimageButton);
        }
        mHeaderHolder.mimageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!click.containsKey(mHeaderHolder.mTextView.getText().toString().trim()) || !click.get(mHeaderHolder.mTextView.getText().toString().trim())) {
                    localUrl.clear();
                    for (int i = 0; i < hasHeaderIdList.size(); i++) {
                        if (TextUtils.equals(mHeaderHolder.mTextView.getText().toString().trim(), hasHeaderIdList.get(i).getTime()) && !SelectedImg.mSelectedImage.contains(hasHeaderIdList.get(i).getTime())) {
                            String path = hasHeaderIdList.get(i).getPath();
                            SelectedImg.mSelectedImage.add(path);
                            localUrl.add(path);
                        }
                    }
                    click.put(mHeaderHolder.mTextView.getText().toString().trim(), true);
                    headView.put(mHeaderHolder.mTextView.getText().toString().trim(), mHeaderHolder.mimageButton);
                    dateUrl.put(mHeaderHolder.mTextView.getText().toString().trim(), localUrl);
                    Log.d("yuhao", "localUrl=" + localUrl.size());
                    notifyDataSetChanged();
                    mHeaderHolder.mimageButton.setImageResource(R.drawable.pic_select_import);
                } else {
                    list.clear();
                    for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                        list.add(SelectedImg.mSelectedImage.get(i));
                    }
                    ListIterator<String> it = list.listIterator();
                    while (it.hasNext()) {
                        String next = it.next();
                        if (TextUtils.equals(mHeaderHolder.mTextView.getText().toString().trim(), getTime(next, dayTime))) {
                            SelectedImg.mSelectedImage.remove(next);
                            List<String> strings = dateUrl.get(getTime(next, dayTime));
                            strings.remove(next);
                            dateUrl.put(mHeaderHolder.mTextView.getText().toString().trim(), strings);
                        }
                    }
                    click.put(mHeaderHolder.mTextView.getText().toString().trim(), false);
                    headView.put(mHeaderHolder.mTextView.getText().toString().trim(), null);
                    notifyDataSetChanged();
                    mHeaderHolder.mimageButton.setImageResource(R.drawable.pic_no_selece_all_import);
                }
            }
        });
        return convertView;
    }

    public void setData(List<YNNativeImage> hasHeaderIdList, boolean dayTime) {
        this.hasHeaderIdList = hasHeaderIdList;
        this.dayTime = dayTime;
        initData();
    }

    private String getTime(String path, boolean dayTime) {
        String dateString = "";
        Date currentTime = new Date(new File(path).lastModified());
        if (dayTime) {
            dateString = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
        } else {
            dateString = new SimpleDateFormat("yyyy-MM").format(currentTime);
        }
        return dateString;
    }

    public class ViewHolder {
        public SimpleDraweeView mImageView;
        public ImageView mNative_item_select;
    }

    public class HeaderViewHolder {
        public TextView mTextView;
        public ImageView mimageButton;
    }
}
